<?php

/**
* 依赖注入
*/
class Ioc
{
    // 获取对象的实例
    public static function getInstance($className)
    {
        $paramArr = self::getMethodParams($className);
        return (new ReflectionClass($className))->newInstanceArgs($paramArr);
    }

    /**
     * 执行类的方法
     * @param $className
     * @param $methodName
     * @param array $params
     */
    public static function make($className, $methodName, $params = [])
    {
        // 获取类的实例
        $instance = self::getInstance($className);

        // 该方法依赖所需要的参数
        $paramArr = self::getMethodParams($className, $methodName);

        return $instance->{$methodName}(...array_merge($paramArr, $params));
    }

    /**
     * 获得类的方法参数，只获得有类型的参数
     * @param  Object $className
     * @param  String $methodsName
     * @return mixed
     */
    protected static function getMethodParams($className, $methodsName = '__construct')
    {
        // 通过反射获取类
        $class = new ReflectionClass($className);
        $paramArr = []; // 记录参数和参数类型

        // 该类是否有构造函数
        if ($class->hasMethod($methodsName)) {
            $construct = $class->getMethod($methodsName);

            // 判断构造函数是否有参数
            $params = $construct->getParameters();

            if (count($params) > 0){
                foreach($params as $key => $param){
                    if ($paramClass = $param->getClass()){
                        // 获取参数类型名称
                        $paramClassName = $paramClass->getName();

                        // 获取参数类型
                        $args = self::getMethodParams($paramClassName);
                        $paramArr[] = (new ReflectionClass($paramClass->getName()))->newInstanceArgs($args);
                    }
                }
            }
        }
        return $paramArr;
    }
}


class A
{
    protected $cObj;

    public function __construct(C $c)
    {
        $this->cObj = $c;
    }

    public function aac()
    {
        $this->cObj->cc();
    }
}

class B
{
    protected $aObj;

    public function __construct(A $a)
    {
        $this->aObj = $a;
    }

    public function bb(C $c, $b)
    {
        $c->cc();
        echo "\r\n";
        echo 'params: '. $b;
    }

    public function bbb()
    {
        $this->aObj->aac();
    }
}

class C
{
    public function cc()
    {
        echo 'this C->cc';
    }
}

$obj = Ioc::getInstance('B');
$obj->bbb();

Ioc::make('B', 'BB', ['this is params']);
